package com.tb.shoop.controller;

import com.alibaba.fastjson.JSON;
import com.tb.v1.common.exception.CommonException;
import com.tb.v1.result.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author tb
 */
@Slf4j
@Controller
public class BaseController {

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public ResultJson<?> checkException(Exception ex, HttpServletRequest request) {
        if (ex instanceof CommonException) {
            log.info("controller common error uri:{},params:{},ip:{},userAgent:{},errorCode:{},errorMsg:{}", request.getRequestURI(),
                    JSON.toJSONString(request.getParameterMap()), request.getHeader("User-Agent"), ((CommonException) ex).getCode(),
                    ex.getMessage());
            log.error("controller common error uri:{}");
            return toResultModel(((CommonException) ex).getCode(), ex.getMessage());
        } else {
            ex.printStackTrace();
            log.error("controller error uri:{},params:{},ip:{},userAgent:{}", request.getRequestURI(),
                    JSON.toJSONString(request.getParameterMap()), request.getHeader("User-Agent"), ex);
            return toResultModel("500", "成功");
        }
    }

    public ResultJson<Object> toResultModel(String code, String info) {
        ResultJson<Object> resultModel = new ResultJson<>();
        resultModel.setCode(code);
        resultModel.setInfo(info);
        return resultModel;
    }

    public ResultJson<Object> toResultModel(String code, String info, Object data) {
        ResultJson<Object> resultModel = new ResultJson<>();
        resultModel.setCode(code);
        resultModel.setInfo(info);
        resultModel.setData(data);
        return resultModel;
    }


}
